package com.lzyyj.gmis.base.webui;

import com.lzyyj.common.ProxyWrapper;
import com.lzyyj.gmis.base.model.IUser;
import com.lzyyj.gmis.base.service.ISystemService;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class WebApplicationImpl implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

    private static final Log log = LogFactory.getLog(WebApplicationImpl.class);

    private static WebApplicationContext context;

    private static String systemServiceBeanName = "LzyyjSystemService";

    private static ISystemService systemService = null;

    public static ISystemService useServiceSystemService() {
        if (systemService == null) {

            if (context == null) {
                log.info("Spring 容器还未初始化，系统初始化操作将被推迟！");
            } else {
                try {
                    systemService = (ISystemService) context.getBean(systemServiceBeanName);
                } catch (BeansException e) {
                    log.debug("通过 Bean name(" + systemServiceBeanName + ") 获取 systemService");
                }
                if (systemService == null) {
                    try {
                        systemService = context.getBean((ISystemService.class));
                    } catch (BeansException e) {
                        log.debug("获取Bean：" + ISystemService.SYSTEM_SERVICE + " 失败！");
                    }
                }
            }
        }
        return systemService;
    }

    private final Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if (context == null) {
            log.error("注意：没有有效的 Spring 环境！");
        } else {

            String paramString = servletContext.getInitParameter("systemServiceBeanName");
            if (paramString != null && !paramString.isEmpty()) {
                systemServiceBeanName = servletContext.getInitParameter("systemServiceBeanName");
            }

            if (useServiceSystemService() == null) {
                log.error("系统配置有误，没有配置 " + ISystemService.SYSTEM_SERVICE + " Bean !");
            } else {
                try {
                    systemService.contextInitialized(context);
                    log.debug("系统启动！");
                } catch (Exception e) {
                    log.error("系统启动失败:" + e);
                }
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        if (systemService != null) {
            try {
                systemService.contextDestroyed();
            } catch (Exception e) {
                log.error("系统停止时发生错误：" + e);
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sessionCreated(HttpSessionEvent sessionEvent) {
        if (systemService == null) {
            useServiceSystemService();
        }
        if (systemService != null) {
            HttpSession session = sessionEvent.getSession();
            Map<String, Object> sessionAttribMap = new HashMap<String, Object>();
            Enumeration<String> s = session.getAttributeNames();
            while (s.hasMoreElements()) {
                String keyString = s.nextElement();
                sessionAttribMap.put(keyString, session.getAttribute(keyString));
            }
            session.getAttributeNames();
            systemService.sessionCreated(session.getId(), sessionAttribMap);
        }
        sessionMap.put(sessionEvent.getSession().getId(), sessionEvent.getSession());
        log.debug("一个节点上线：" + sessionEvent.getSession().getId());
        log.debug("当前在线节点数：" + sessionMap.size());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent sessionEvent) {
        sessionMap.remove(sessionEvent.getSession().getId());
        log.debug("一个节点下线：" + sessionEvent.getSession().getId());
        log.debug("当前在线节点数：" + sessionMap.size());
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent arg0) {
        useServiceSystemService();
        String keyString = arg0.getName();
        String userKey = null;
        for (String key : "user,manage".split(",")) {
            if (keyString.toLowerCase().endsWith(key)) {
                userKey = keyString;
                break;
            }
        }
        if (userKey != null) {
            if (systemService != null) {
                IUser<Serializable> user = null;
                Object sourceObject = arg0.getValue();
                if (sourceObject instanceof IUser) {
                    user = (IUser<Serializable>) sourceObject;
                    systemService.logined(user);
                } else {
                    log.debug("not is IUser");
                }
            } else {
                log.debug("有用户登录:" + arg0.getName() + "(" + arg0.getValue() + ")");
            }
        } else {
            log.debug("session有添加:" + arg0.getName() + "(" + arg0.getValue() + ")");
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
        useServiceSystemService();
        String keyString = arg0.getName();
        String userKey = null;
        for (String key : "user,manage".split(",")) {
            if (keyString.toLowerCase().endsWith(key)) {
                userKey = keyString;
                break;
            }
        }
        if (userKey != null) {
            if (systemService != null) {
                IUser user;
                try {
                    user = ProxyWrapper.createProxyBean(IUser.class, "loginName,name", arg0.getValue());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    user = null;
                }
                systemService.logouted(user);
            }
            log.debug("有用户注销");
            log.debug("有用户注销:" + arg0.getName() + "(" + arg0.getValue() + ")");
        } else {
            log.debug("session有删除:" + arg0.getName() + "(" + arg0.getValue() + ")");
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub

    }

}
